import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:simple_app/chat.dart';
import 'package:simple_app/common/global.dart';
import 'package:simple_app/common/message/relay.dart';
import 'package:simple_app/common/model/message.dart';

import 'package:simple_app/common/api.dart';

class MessageListPage extends StatefulWidget {
  const MessageListPage({Key? key}) : super(key: key);

  @override
  State<MessageListPage> createState() => _MessageListPageState();
}

class _MessageListPageState extends State<MessageListPage> {
  var itemCount = 0;
  List<Message> list = [];

  //列表数据
  Future<void> getList() async {
    var r = await Api().messageList();
    if (r == null) {
      return;
    }
    if (r.statusCode != 200) {
      return;
    }
    if (r.statusCode == 200) {
      Map<String, dynamic> data = jsonDecode(r.body);
      if (data['status'] == 1) {
        List<dynamic> list2 = data['list'];
        setState(() {
          list.clear();
          for (var element in list2) {
            list.add(Message.fromJson(element));
          }
          itemCount = list.length;
        });
      }
    }
    return;
  }

  var listenid = -1;

  //获取双向通讯信息
  receiveMessage(jsonobj) {
    if (jsonobj['type'] == "relay") {
      var data = Relay.fromJson(jsonobj);
      var index = -1;
      setState(() {
        for (var i = 0; i < list.length; i++) {
          if (list[i].receiver == data.sender ||
              list[i].sender == data.sender) {
            list.insert(
                0,
                Message(
                    id: list[i].id,
                    name: list[i].name,
                    sender: list[i].sender,
                    receiver: list[i].receiver,
                    msg: data.data.toString(),
                    isRead: 0,
                    addTime: list[i].addTime));
            index = i + 1;
            break;
            // list[i].msg = data.data.toString();
          }
        }
      });
      if (index != -1) {
        //刷新第二次
        setState(() {
          list.removeAt(index);
        });
      }
    }
  }

  @override
  void initState() {
    super.initState();
    getList();
    if (listenid == -1) {
      listenid = Global.listenMessage(receiveMessage);
    }
  }

  @override
  void dispose() {
    super.dispose();
    if (listenid != -1) {
      Global.removeListenMessage(listenid);
    }
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
        onRefresh: onRefresh,
        child: ListView.builder(
            itemCount: itemCount,
            itemBuilder: (context, index) {
              var msgtxt = Text(list[index].msg);
              var redmsgtxt = Text(
                list[index].msg,
                style: const TextStyle(color: Color.fromARGB(255, 204, 0, 0)),
              );

              return GestureDetector(
                child: ListTile(
                  title: Text(list[index].name),
                  subtitle: list[index].isRead == 1
                      ? msgtxt
                      : (list[index].receiver == Api.userInfo.id
                          ? redmsgtxt
                          : msgtxt),
                ),
                onTap: () {
                  //点击进入chat页面
                  var friendid = list[index].receiver;
                  if (friendid == Api.userInfo.id) {
                    friendid = list[index].sender;
                  }
                  print('$index===>$friendid===>${Api.userInfo.id}');

                  setState(() {
                    var newmsg = Message(
                        id: list[index].id,
                        name: list[index].name,
                        sender: list[index].sender,
                        receiver: list[index].receiver,
                        msg: list[index].msg,
                        isRead: 1,
                        addTime: list[index].addTime);
                    list.insert(index, newmsg);
                  });
                  setState(() {
                    list.removeAt(index + 1);
                  });

                  Navigator.pushNamed(context, "/chat",
                      arguments:
                          ChatRouteArgs(name: list[index].name, id: friendid));
                },
              );
            }));
  }

  Future<void> onRefresh() {
    return getList();
  }
}
